﻿using Furion.RemoteRequest.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Options;
using ProjectManage.Core.Dto.WeChat;
using ProjectManage.Core.Entity;
using ProjectManage.Core.Entity.SYS;
using ProjectManage.Core.Enum;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Reflection.Emit;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace ProjectManage.Application.System.Services
{
    /// <summary>
    /// 系统服务
    /// </summary>
    [ApiDescriptionSettings(Name = "SYS", Order = 160)]
    [Route("api")]
    public class SystemService : ISystemService, ITransient
    {
        private readonly IRepository<SysUser> _repository;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public SystemService(IRepository<SysUser> repository, IHttpContextAccessor httpContextAccessor)
        {
            _repository = repository;
            _httpContextAccessor = httpContextAccessor;
        }


        #region 通用方法
        /// <summary>
        /// 通用批量删除   
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task DeleteMutiAsync<T>(List<DeleteDto> input)
        {
            var deletes = input.Adapt<List<T>>();
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                foreach (var item in deletes)
                {
                    ef.Attach(item);
                    ef.Remove(item);
                }

                await ef.SaveChangesAsync();
            }

        }

        /// <summary>
        /// 通用更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateAsync<TDataBase, TUpdateDto>(TUpdateDto input) where TDataBase : DBEntityBase<Guid, MasterDbContextLocator> where TUpdateDto : BaseUpdate
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {

                var dbEntity = ef.Set<TDataBase>().AsNoTracking().FirstOrDefault(o => o.Id == input.id);
                if (dbEntity == null)
                    throw Oops.Oh("更新的数据不存在，请检查是否已被删除");

                dbEntity = input.Adapt<TDataBase>();
                dbEntity.ModifiedTime = DateTime.Now;
                ef.Entry(dbEntity).State = EntityState.Modified;
                await ef.SaveChangesAsync();
            }
        }
        #endregion

        #region 用户相关服务
        /// <summary>
        /// 新增  
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddUserAsync(AddUserDto input)
        {
            if (_repository.Any(o => o.Account == input.Account))
            {
                throw Oops.Oh("账号已存在，无法重复添加！");
            }

            var user = input.Adapt<SysUser>();
            user.Id = Guid.NewGuid();
            user.Password = MD5Encryption.Encrypt(input.Password);
            user.CreatedTime = DateTime.Now;
            await _repository.InsertAsync(user);
        }


        /// <summary>
        /// 批量删除   
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task DeleteMutiUserAsync(List<DeleteDto> input)
        {
            var users = input.Adapt<List<SysUser>>();
            await _repository.DeleteAsync(users);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<PagedList<QueryUserDto>> QueryUserAsync(QueryParameter options)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var sysUsers = ef.Set<SysUser>().AsQueryable();

                //模糊搜索
                if (!string.IsNullOrEmpty(options.SearchText))
                {
                    sysUsers.Where(o => o.Account.Contains(options.SearchText) || o.Name.Contains(options.SearchText));
                }
                //筛选
                sysUsers = sysUsers.DynamicWhere(options.Searchs);

                //分页
                return await sysUsers.Select(o => o.Adapt<QueryUserDto>()).ToPagedListAsync(options.PageIndex, options.PageItems);

            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateUserAsync(UpdateUserDto input)
        {
            var user = input.Adapt<SysUser>();
            user.Password = MD5Encryption.Encrypt(user.Password);
            user.ModifiedTime = DateTime.Now;
            await _repository.UpdateIncludeAsync(user, new[] { "Name", "Password", "ModifiedName", "ModifiedTime" });
        }


        #endregion

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task<TokenModel> LoginAsync(LoginDto input)
        {

            var password = MD5Encryption.Encrypt(input.Password);
            var user = _repository.FirstOrDefault(o => o.Password == password && o.Account == input.Account);

            if (user == null)
            {
                throw Oops.Oh($"用户名或者密码不正确！");
            }

            var now = DateTime.Now;
            // token
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {
                { "ID", user.Id },  // 存储用户名
                { "Account",input.Account }, // 存储密码
                { "Expr", now }, // 过期时间
            });

            // 获取刷新 token
            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 43200); // 第二个参数是刷新 token 的有效期（分钟），默认三十天

            TokenModel token = new TokenModel()
            {
                Account = input.Account,
                UserName = user.Name,
                //AccessToken = accessToken,
                //RefreshToken = refreshToken,
                //AccessExpir = now.AddMinutes(Double.Parse(App.Configuration["JWTSettings:ExpiredTime"])),
            };

            // 设置响应报文头
            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
            _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;

            return Task.FromResult(token);
        }

        /// <summary>
        /// 三方登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<TokenModel> ThreeLoginAsync(LoginDto input)
        {
            //获取Token
            var tokenResult = await "gettoken".SetClient("WeChat").SetQueries(new Dictionary<string, object>
            {
                 { "corpid", App.Configuration["WeChat:appid"]},
                 { "corpsecret",App.Configuration[$"WeChat:{input.Password}"]}
            }).GetAsAsync<TokenResult>();

            if (tokenResult.errcode != 0)
            {
                throw Oops.Oh(tokenResult.errmsg);
            }

            //获取用户名
            var userid = await "auth/getuserinfo".SetClient("WeChat").SetQueries(new Dictionary<string, object>
            {
                 { "access_token",tokenResult.access_token},
                 { "code", input.Account}
            }).GetAsAsync<TokenResult>();

            if (tokenResult.errcode != 0)
            {
                throw Oops.Oh(userid.errmsg);
            }

            //获取姓名
            var userName = await "user/get".SetClient("WeChat").SetQueries(new Dictionary<string, object>
            {
                 { "access_token",tokenResult.access_token},
                 { "userid", userid.userid}
            }).GetAsAsync<TokenResult>();

            if (tokenResult.errcode != 0)
            {
                throw Oops.Oh(userName.errmsg);
            }

            //获取敏感数据
            var usrInfo = await "auth/getuserdetail".SetClient("WeChat").SetQueries(new Dictionary<string, object>
            {
                 { "access_token",tokenResult.access_token}
            })
            .SetBody(new { userid.user_ticket }, "application/json")
            .PostAsAsync<UserInfoResult>();

            if (usrInfo.errcode != 0)
            {
                throw Oops.Oh(usrInfo.errmsg);
            }

            //第一次时新增用户表数据 并自动绑定对应应用角色 对应应用角色需手动创建赋值菜单
            var id = Guid.NewGuid();
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var sysUserRole = ef.Set<SysUserRole>().FirstOrDefault(o => o.RoleCode == input.Password);
                if (sysUserRole == null)
                {
                    sysUserRole.Id = Guid.NewGuid();
                    sysUserRole.Account = userid.userid;
                    sysUserRole.RoleCode = input.Password;
                    sysUserRole.Creater = "Admin";
                    sysUserRole.CreatedName = "管理员";
                    sysUserRole.CreatedTime = DateTime.Now;
                }

                var sysUsers = ef.Set<SysUser>().FirstOrDefault(o => o.Account == userid.userid);
                if (sysUsers == null)
                {
                    sysUsers.Id = id;
                    sysUsers.Account = userid.userid;
                    sysUsers.Name = userName.name;
                    sysUsers.Avatar = usrInfo.avatar;
                    sysUsers.Password = MD5Encryption.Encrypt("Aa123456");
                    sysUsers.CreatedName = "管理员";
                    sysUsers.CreatedTime = DateTime.Now;

                    await ef.SaveChangesAsync();
                }
            }

            var now = DateTime.Now;
            // token
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {
                { "ID", id },  // 存储用户名
                { "Account",userid.userid }, // 存储密码
                { "Expr", now.AddMinutes(Double.Parse(App.Configuration["JWTSettings:ExpiredTime"])) }, // 过期时间
            });

            // 获取刷新 token
            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 43200 * 12); // 第二个参数是刷新 token 的有效期（分钟），默认三十天

            TokenModel token = new TokenModel()
            {
                Account = userid.userid,
                UserName = userName.name,
                AppCode = input.Password,
                Avatar = usrInfo.avatar,
                //AccessToken = accessToken,
                //RefreshToken = refreshToken,
                //AccessExpir = now.AddMinutes(Double.Parse(App.Configuration["JWTSettings:ExpiredTime"])),
            };

            // 设置响应报文头
            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
            _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;

            return token;
        }

        #endregion

        #region 角色相关服务
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddRoleAsync(AddRoleDto input)
        {
            var repository = Db.GetRepository<SysRole>();

            if (repository.Any(o => o.RoleCode == input.RoleCode))
            {
                throw Oops.Oh("角色已存在，无法重复添加！");
            }

            var sysRole = input.Adapt<SysRole>();
            sysRole.Id = Guid.NewGuid();
            sysRole.CreatedTime = DateTime.Now;
            await repository.InsertAsync(sysRole);
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateRoleAsync(UpdateRoleDto input)
        {
            var repository = Db.GetRepository<SysRole>();
            var sysRole = input.Adapt<SysRole>();
            sysRole.ModifiedTime = DateTime.Now;
            await repository.UpdateIncludeAsync(sysRole, new[] { "RoleName", "Modifier", "ModifiedName", "ModifiedTime" });
        }

        /// <summary>
        /// 批量删除角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task DeleteMutiRoleAsync(List<DeleteDto> input)
        {
            var repository = Db.GetRepository<SysRole>();
            var deleteDtos = input.Adapt<List<SysRole>>();
            await repository.DeleteAsync(deleteDtos);
        }

        /// <summary>
        /// 查询角色
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<PagedList<QueryRoleDto>> QueryRoleAsync(QueryParameter options)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var sysRoles = ef.Set<SysRole>().AsQueryable();

                //模糊搜索
                if (!string.IsNullOrEmpty(options.SearchText))
                {
                    sysRoles.Where(o => o.RoleCode.Contains(options.SearchText) || o.RoleName.Contains(options.SearchText));
                }
                //筛选
                sysRoles = sysRoles.DynamicWhere(options.Searchs);

                //分页
                return await sysRoles.Select(o => o.Adapt<QueryRoleDto>()).ToPagedListAsync(options.PageIndex, options.PageItems);

            }
        }

        #endregion

        #region 数据字典相关服务

        /// <summary>
        /// 新增数据字典
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddDictionaryAsync(AddDictionaryDto input)
        {
            var repository = Db.GetRepository<SysDictionary>();

            if (repository.Any(o => o.DictionaryType == input.DictionaryType && o.DictionaryValue == input.DictionaryValue))
            {
                throw Oops.Oh($"数据字典类别{input.DictionaryType}中的值{input.DictionaryValue}已存在，无法重复添加！");
            }

            var sysDictionary = input.Adapt<SysDictionary>();
            sysDictionary.Id = Guid.NewGuid();
            sysDictionary.CreatedTime = DateTime.Now;
            await repository.InsertAsync(sysDictionary);
        }

        /// <summary>
        /// 查询数据字典
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<PagedList<QueryDictionaryDto>> QueryDictionaryAsync(QueryParameter options)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var sysDictionaries = ef.Set<SysDictionary>().AsQueryable();

                //模糊搜索
                if (!string.IsNullOrEmpty(options.SearchText))
                {
                    sysDictionaries.Where(o => o.DictionaryType.Contains(options.SearchText)
                   || o.DictionaryTypeName.Contains(options.SearchText)
                   || o.DictionaryValue.Contains(options.SearchText)
                   || o.DictionaryDescription.Contains(options.SearchText));
                }
                //筛选
                sysDictionaries = sysDictionaries.DynamicWhere(options.Searchs);

                //分页
                return await sysDictionaries.OrderBy(o => o.DictionaryType).ThenBy(o => o.DictionaryValue).Select(o => o.Adapt<QueryDictionaryDto>()).ToPagedListAsync(options.PageIndex, options.PageItems);

            }
        }


        /// <summary>
        /// 根据类别查询数据字典
        /// </summary>
        /// <param name="type">类别</param>
        /// <returns></returns>
        public async Task<List<SelectedItem>> QueryDictionaryByTypeAsync(string type)
        {
            var sysDictionaries = Db.GetRepository<SysDictionary>();
            return await sysDictionaries
                .Where(o => o.DictionaryType == type)
                .OrderBy(o => o.DictionaryType)
                .ThenBy(o => o.DictionaryValue)
                .Select(o => new SelectedItem
                {
                    Text = o.DictionaryDescription,
                    Value = o.DictionaryValue
                }).ToListAsync();
        }
        #endregion


        #region 菜单

        /// <summary>
        /// 新增菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddMenuAsync(AddMenuDto input)
        {
            var repository = Db.GetRepository<SysMenu>();

            if (repository.Any(o => o.AppCode == input.AppCode && o.ParentCode == input.ParentCode && o.MenuCode == input.MenuCode))
            {
                throw Oops.Oh($"{input.AppCode}应用，已添加{input.MenuCode}菜单！");
            }

            var sysMenu = input.Adapt<SysMenu>();
            sysMenu.Id = Guid.NewGuid();
            sysMenu.CreatedTime = DateTime.Now;
            await repository.InsertAsync(sysMenu);
        }


        /// <summary>
        /// 查询菜单
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<List<QueryMenuDto>> QueryMenuAsync()
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var sysEntity = ef.Set<SysMenu>().AsQueryable().OrderBy(o=> o.MenuCode);

                //分页
                return await sysEntity.Select(o => o.Adapt<QueryMenuDto>()).ToListAsync();
            }
        }

        /// <summary>
        /// 查询角色菜单根据角色编号
        /// </summary>
        /// <param name="RoleCode">角色编码</param>
        /// <returns></returns>
        public async Task<List<QueryMenuDto>> QueryMenusByRoleCodeAsync(string RoleCode)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var query = from a in ef.Set<SysMenu>()
                            where ef.Set<SysRoleMenu>().Any(p => p.RoleCode == RoleCode && p.MenuCode == a.MenuCode)
                            select a.Adapt<QueryMenuDto>();

                return await query.OrderBy(o => o.MenuCode).ToListAsync();
            }
        }

        /// <summary>
        /// 查询按钮权限
        /// </summary>
        /// <param name="Account"></param>
        /// <returns></returns>
        public async Task<List<QueryMenuDto>> QueryButtonsByAccountAsync(string Account)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var isSuperAdmin = ef.Set<SysUserRole>().Any(o => o.Account == Account && o.RoleCode == "SystemAdmin");
                var query = (from a in ef.Set<SysUserRole>()
                             join b in ef.Set<SysRoleMenu>() on a.RoleCode equals b.RoleCode
                             where a.Account == Account
                             select b.MenuCode).ToList();


                var result = from a in ef.Set<SysMenu>()
                             where isSuperAdmin || query.Contains(a.MenuCode)
                             && a.MenuType == "2"
                             select new QueryMenuDto
                             {
                                  Id = a.Id,
                                  MenuCode = a.MenuCode,
                                  ParentCode = a.ParentCode,
                             };

                return  await result.ToListAsync();
            }
        }

        /// <summary>
        /// 查询菜单根据账号和APP编号
        /// </summary>
        /// <param name="Account"></param>
        /// <param name="AppCode"></param>
        /// <returns></returns>
        public async Task<List<QueryMenuItem>> QueryMenusByAccountAsync(string Account,string AppCode)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var isSuperAdmin = ef.Set<SysUserRole>().Any(o => o.Account == Account && o.RoleCode == "SystemAdmin");
                var query = (from a in ef.Set<SysUserRole>()
                            join b in ef.Set<SysRoleMenu>() on a.RoleCode equals b.RoleCode
                            where a.Account == Account
                            select b.MenuCode).ToList();


                var result = from a in ef.Set<SysMenu>()
                             where isSuperAdmin|| query.Contains(a.MenuCode)
                             select a;

                if (!string.IsNullOrEmpty(AppCode))
                {
                    result = result.Where(o => o.AppCode == AppCode);
                }


                return QueryMenuItems(await result.OrderBy(o => o.MenuCode).ToListAsync(), null);
            }
        }

        //获取编号
        private List<QueryMenuItem> QueryMenuItems(IEnumerable<SysMenu> items, string? parentCode)
        {
            var ret = new List<QueryMenuItem>();
            ret.AddRange(items.Where(i => i.ParentCode == parentCode).Select((menu, index) => new QueryMenuItem
            {
                Text = menu.Name,
                Icon = $"fa-solid fa-fw {menu.Icon}",
                Url = menu.Url,
                // 获得子项集合
                Items = QueryMenuItems(items.Where(i => i.ParentCode == menu.MenuCode), menu.MenuCode)
            }));
            return ret;
        }
        #endregion

        #region 用户角色

        /// <summary>
        /// 新增用户角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddUserRoleAsync(AddUserRoleDto input)
        {
            var repository = Db.GetRepository<SysUserRole>();

            if (repository.Any(o => o.Account == input.Account && o.RoleCode == input.RoleCode))
            {
                throw Oops.Oh($"用户{input.Account}，已添加{input.RoleCode}用户角色！");
            }

            var sysUserRole = input.Adapt<SysUserRole>();
            sysUserRole.Id = Guid.NewGuid();
            sysUserRole.CreatedTime = DateTime.Now;
            await repository.InsertAsync(sysUserRole);
        }

        /// <summary>
        /// 查询用户角色
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<PagedList<QueryUserRoleDto>> QueryUserRoleAsync(QueryParameter options)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var sysEntity = ef.Set<SysUserRole>().AsQueryable();
                //筛选
                sysEntity = sysEntity.DynamicWhere(options.Searchs);

                var query = from a in sysEntity
                            join b in ef.Set<SysUser>() on a.Account equals b.Account
                            join c in ef.Set<SysRole>() on a.RoleCode equals c.RoleCode
                            select new QueryUserRoleDto
                            {
                                Id = a.Id,
                                RoleCode = a.RoleCode,
                                RoleName = c.RoleName,
                                Account = a.Account,
                                AccountName = b.Name,
                                Creater = a.Creater,
                                CreatedName = a.CreatedName,
                                CreatedTime = a.CreatedTime,
                                Modifier = a.Modifier,
                                ModifiedName = a.ModifiedName,
                                ModifiedTime = a.ModifiedTime

                            };

                //模糊搜索
                if (!string.IsNullOrEmpty(options.SearchText))
                {
                    query.Where(o => o.RoleCode.Contains(options.SearchText)
                     || o.Account.Contains(options.SearchText)
                     || o.RoleName.Contains(options.SearchText)
                     || o.AccountName.Contains(options.SearchText));
                }




                //分页
                return await query.ToPagedListAsync(options.PageIndex, options.PageItems);
            }
        }
        #endregion


        #region 角色菜单

        /// <summary>
        /// 新增角色菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AddRoleMenuAsync(AddRoleMenuDto input)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                foreach (var item in input.MenuCodes)
                {
                    var sysRoleMenu = input.Adapt<SysRoleMenu>();
                    sysRoleMenu.Id = Guid.NewGuid();
                    sysRoleMenu.CreatedTime = DateTime.Now;
                    sysRoleMenu.MenuCode = item;
                    await ef.AddAsync(sysRoleMenu);
                }
                await ef.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 更新角色菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateRoleMenuAsync(UpdateRoleMenuDto input)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var menus = ef.Set<SysRoleMenu>().AsNoTracking().Where(o => input.RoleCode == o.RoleCode).ToList();

                foreach (var item in input.MenuCodes)
                {
                    var sysRoleMenus = menus.FirstOrDefault(o => o.MenuCode == item);
                    if (sysRoleMenus == null)
                    {
                        var sysRoleMenu = input.Adapt<SysRoleMenu>();
                        sysRoleMenu.Id = Guid.NewGuid();
                        sysRoleMenu.CreatedTime = DateTime.Now;
                        sysRoleMenu.MenuCode = item;
                        await ef.AddAsync(sysRoleMenu);
                    }
                    else
                    {
                        menus.Remove(sysRoleMenus);
                    }
                }

                if (menus.Count > 0)
                {
                    ef.Set<SysRoleMenu>().RemoveRange(menus);
                }
                await ef.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 查询角色菜单
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<PagedList<QueryRoleMenuDto>> QueryRoleMenuAsync(QueryParameter options)
        {
            using (var ef = Db.GetDbContext(typeof(MasterDbContextLocator)))
            {
                var sysEntity = ef.Set<SysRoleMenu>().AsQueryable();
                //筛选
                sysEntity = sysEntity.DynamicWhere(options.Searchs);

                var query = from a in sysEntity
                            join b in ef.Set<SysMenu>() on a.MenuCode equals b.MenuCode
                            join c in ef.Set<SysRole>() on a.RoleCode equals c.RoleCode
                            select new QueryRoleMenuDto
                            {
                                Id = a.Id,
                                RoleCode = a.RoleCode,
                                RoleName = c.RoleName,
                                MenuCode = a.MenuCode,
                                Name = b.Name,
                                Creater = a.Creater,
                                CreatedName = a.CreatedName,
                                CreatedTime = a.CreatedTime,
                                Modifier = a.Modifier,
                                ModifiedName = a.ModifiedName,
                                ModifiedTime = a.ModifiedTime

                            };

                //模糊搜索
                if (!string.IsNullOrEmpty(options.SearchText))
                {
                    query.Where(o => o.RoleCode.Contains(options.SearchText)
                     || o.MenuCode.Contains(options.SearchText)
                     || o.RoleName.Contains(options.SearchText)
                     || o.Name.Contains(options.SearchText));
                }

                //分页
                return await query.ToPagedListAsync(options.PageIndex, options.PageItems);
            }
        }


        #endregion
    }
}